<template>
  <Form ref="user" :model="user" :rules="ruleValidate">
    <FormItem label="登录名" prop="username">
      <Input v-model="user.username" placeholder="登录名"></Input>
    </FormItem>
    <FormItem label="邮箱" prop="email">
      <Input v-model="user.email" placeholder="邮箱"></Input>
    </FormItem>
    <FormItem label="密码" prop="password">
      <Input type="password" v-model="user.password" placeholder="密码"></Input>
    </FormItem>
    <FormItem label="重复密码" prop="rePasswrod">
      <Input type="password" v-model="user.rePasswrod" placeholder="再次输入密码"></Input>
    </FormItem>

    <FormItem>
      <Button @click="handleReset('user')">重置</Button>
      <Button type="primary" style="margin-left: 8px" @click="handleSubmit('user')">创建</Button>
    </FormItem>
  </Form>
</template>
<script>
  import {mapState, mapActions} from 'vuex'

  export default {
    components: {

    },
    computed: {

    },
    data() {
      const vm = this
      const checkPwd = function (rule, value, callback) {
        if (value !== vm.user.password) {
          return callback(new Error('两次输入的密码不一致'));
        }
        callback();
      }

      return {
        user: {
          username: '',
          email: '',
          password:'',
          rePasswrod:''
        },
        ruleValidate: {
          username: [
            {required: true, message: '登录名不能为空', trigger: 'blur'},
          ],
          email:{required: true, message: '邮箱不能为空', trigger: 'blur'},
          password:{required: true, message: '密码不能为空', trigger: 'blur'},
          rePasswrod:{required: true, validator:checkPwd, trigger: 'blur'}
        }
      }
    },
    created() {

    },
    methods: {
      ...mapActions({
        createUser: 'user/userRegister'
      }),

      // 提交
      handleSubmit(name) {
        this.$refs[name].validate(async (valid) => {
          if (valid) {
            try {
              await this.createUser(this.user);
              this.$Message.success('创建用户成功');
              // window.location.href = "/category/list";
              this.handleReset('user');

            } catch (e) {
              this.$Message.error(e)

            }
          } else {
            this.$Message.error('干哈呢，你!');
          }
        })
      },
      handleReset(name) {
        this.$refs[name].resetFields();
      }
    }
  }
</script>
